package com.dp.springsourcecodeanalysis.web.messagerConverters;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;

import org.springframework.http.HttpInputMessage;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.util.StreamUtils;

import com.dp.springsourcecodeanalysis.web.dto.UserResponseDTO;

/**
 * Created by IntelliJ IDEA
 *
 * @author shala/沙拉
 * @date 2022/1/20 15:09
 */
public class TempMessageConverter implements HttpMessageConverter<UserResponseDTO> {
    private static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");

    @Override
    public boolean canRead(Class<?> clazz, MediaType mediaType) {
        return false;
    }

    @Override
    public boolean canWrite(Class<?> clazz, MediaType mediaType) {
        return UserResponseDTO.class.isAssignableFrom(clazz);
    }

    @Override
    public List<MediaType> getSupportedMediaTypes() {
        return MediaType.parseMediaTypes("application/xxx-shala");
    }

    @Override
    public UserResponseDTO read(Class<? extends UserResponseDTO> clazz, HttpInputMessage inputMessage)
        throws IOException, HttpMessageNotReadableException {
        return null;
    }

    @Override
    public void write(UserResponseDTO userResponseDTO, MediaType contentType, HttpOutputMessage outputMessage)
        throws IOException, HttpMessageNotWritableException {
        String msg = "username:" + userResponseDTO.getUsername() + ";" + "nickname:" + userResponseDTO.getNickname()
            + ";" + "age:" + userResponseDTO.getAge();
        StreamUtils.copy(msg, DEFAULT_CHARSET, outputMessage.getBody());
    }
}
